
package com.kyrie.lib_sys.exception;

import com.kyrie.lib_sys.application.timeApplys.pojo.entity.ValidationResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理    @RestControllerAdvice+@ExceptionHandler 好比就是@configuration+@bean
 *
 * @author heefM
 * @date 2025-
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ValidationResult handleValidationExceptions(MethodArgumentNotValidException ex) {
        ValidationResult result = new ValidationResult();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
            result.addError(error.getField() + ": " + error.getDefaultMessage());
        });
        return result;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ValidationResult handleAllExceptions(Exception ex) {
        ValidationResult result = new ValidationResult();
        result.addError("全局异常处理-->服务器内部错误: " + ex.getMessage());
        return result;
    }

}